local P = ClassFromFile(...)

P.LoginPhase = 
{
	unknown = 0,
	login = 1,
	createAccount = 2,
	getAvatarList = 3,
	createAvatar = 4,
	enterGame = 5,
}

P.identity = false
P.isAdult = true
P.ServerInfos = nil
P.reLoginNum = 0
P.curServerInfo = nil

function P.Init(callback)
	--if P.callback then
	--	P.callback = callback
	--	return true, false
	--end
	--P.callback = callback

	--P.callback = callback
	P.callcack1 = Event.AddListener("onLoginSuccessfully", P.onLoginSuccessfully);
	P.callcack2 = Event.AddListener("onLoginFailed", P.onLoginFailed);
	P.callcack3 = Event.AddListener("onCreateAccountResult", P.onCreateAccountResult);
	P.callcack4 = Event.AddListener("onReqAvatarList", P.onReqAvatarList);
	P.callcack5 = Event.AddListener("onCreateAvatarResult", P.onCreateAvatarResult);
	P.callcack6 = Event.AddListener("Net_CanUse", P.Net_CanUse)
	table.insert(KBEngineLua.OnDisconnect, P.OnDisconnect)
	table.insert(KBEngineLua.OnReloginBaseapp, P.OnReloginBaseapp)

	P.randNum = math.random()
	return true, true, P.randNum
end

function P.OnDisconnect()
	if P.timer then
		return
	end
	logError("OnDisconnect")
	RootWindowManager.instance:HideWindow("LoadingDialog")
	RootWindowManager.instance:ShowWindow("LoadingDialog", false):Init({content = "重连中..."})
	P.timer = TimerEx.New(P.ReLogin, 2, 2, -1)
	P.timer:Start()
end

function P.OnReloginBaseapp(success)
	logError("OnReloginBaseapp "..tostring(success))
	if success then
		P.StopReLogin()
	end
end

function P.ReLogin()
	log("ReLogin")
	if P.reLoginNum > 10 then
		RootWindowManager.instance:ShowWindow("OneBtnDialog", false):Init({content = "重连失败"})
		P.StopReLogin()
		return
	end
	P.reLoginNum = P.reLoginNum + 1
	KBEngineLua.reLoginBaseapp()
end

function P.StopReLogin()
	RootWindowManager.instance:HideWindow("LoadingDialog")
	logError("StopReLogin")
	P.reLoginNum = 0
	P.timer:Stop()
	P.timer = nil
end

function P.SetServers(serverInfos)
	P.serverInfos = serverInfos
	--SettingEx.string.ServerIP = "127.0.0.1"
	--SettingEx.int.ServerID = 5
	--local serverInfos = self._funObj:GetServerInfos()

	--上次登录服务器
	if SettingEx.string.ServerIP and SettingEx.int.ServerID then
		for i = 0, serverInfos.Length - 1 do
			local serverInfo = serverInfos[i]
			if SettingEx.int.ServerID == serverInfo.id then
				LoginHelper.SetServerInfo(serverInfo)
				return
			end
		end
	end

	--首次登录默认服务器
	local recommendedServer = nil
	local newServer = serverInfos[0]
	for i = 0, serverInfos.Length - 1 do
		local serverInfo = serverInfos[i]
		if serverInfo.is_recommended then
			recommendedServer = serverInfo
		end
		if serverInfo.is_new then
			newServer = serverInfo
		end
	end
	if recommendedServer then
		LoginHelper.SetServerInfo(recommendedServer)
	end
end

function P.Net_CanUse(errorCode, name)
	logError("Net_CanUse errorCode "..tostring(errorCode).."  name:"..name)
end
function P.Destroy(randNum)
	if randNum ~= P.randNum then
		return false
	end

	if not P.randNum then
		return true
	end

	P.randNum = nil

	P.callback = nil

	if P.callcack1 then
		P.callcack1.disconnect()
		P.callcack1 = nil
	end

	if P.callcack2 then
		P.callcack2.disconnect()
		P.callcack2 = nil
	end

	if P.callcack3 then
		P.callcack3.disconnect()
		P.callcack3 = nil
	end

	if P.callcack4 then
		P.callcack4.disconnect()
		P.callcack4 = nil
	end

	if P.callcack5 then
		P.callcack5.disconnect()
		P.callcack5 = nil
	end

	if P.callcack6 then
		P.callcack6.disconnect()
		P.callcack6 = nil
	end

	return true
end

function P.onLoginSuccessfully()
	-- log("onLoginSuccessfully")
	--if P.callback then
	--	P.callback(P.phase, 0)
	--end

	-- logError("reqAvatarList: "..tostring(os.time()))
	--P.phase = P.LoginPhase.getAvatarList
	log("onLoginSuccessfully")
	KBEngineLua.player().baseCall.reqAvatarList()
	if AndroidHelper.OnEventLogin then
		local channel = "official"
		if quicksdk then
			channel = tostring(quicksdk.QuickSDK.getInstance():channelType())
		end
		AndroidHelper.OnEventLogin(channel, true)
	end
end

function P.onLoginFailed(errorCode)
	if errorCode == ErrorCode.LoginFailed_NoUser then
		P.Register(P.username, P.password, P.userAc)
	else
		RootWindowManager.instance:HideWindow("LoadingDialog")
		if errorCode == 1 then
			errorCode = "ServerNotReady"
			local winProxy2 = RootWindowManager.instance:ShowWindow("OneBtnDialog",false);
			winProxy2:Init({title = LuaTextKey.prompt_title, content=errorCode, okBtnText=LuaTextKey.ok});
		end
		logError("onLoginFailed errorCode: "..tostring(errorCode))
		ShowErrorMessageByErrorCode(errorCode)
	end
end

function P.onCreateAccountResult(errorCode)
	-- log("onCreateAccountResult"..errorCode)
	--if P.callback then
	--	P.callback(P.phase, errorCode)
	--end

	if errorCode == 0 then
		P.Login(P.username, P.password)
	else
		logError("onCreateAccountResult:"..errorCode)
	end

	if AndroidHelper.OnEventRegister then
		local channel = "official"
		if quicksdk then
			channel = tostring(quicksdk.QuickSDK.getInstance():channelType())
		end
		local success = errorCode == 0 and true or false
		AndroidHelper.OnEventRegister(channel, success)
	end
end

-- 请求角色列表返回
function P.onReqAvatarList(avatarList, serverTime)
	log("onReqAvatarList")
	local avatar = nil
	for dbid, value in pairs(avatarList) do
		avatar = value
		break
	end
	if avatar then
		P.EnterGame(avatar.dbid)
	else
		log("reqCreateAvatar")
		RootWindowManager.instance:HideWindow("LoadingDialog")
		RootWindowManager.instance:ShowWindow("CreateRoleWindow"):Init()
		--KBEngineLua.player().baseCall.reqCreateAvatar(P.username, 1)
	end

	P.serverTimeMinusClientTime = serverTime - os.time()
	
	-- logError("test_server_time: "..tostring(os.time()).."  "..tostring(serverTime).."  "..tostring(P.serverTimeMinusClientTime))
	--if P.callback then
	--	P.callback(P.phase, 0, avatarList)
	--end

	--local avatar
	--for key, value in pairs(avatarList) do
	--	avatar = value
	--	break
	--end
	
	--if avatar ~= nil then
	--	local p = KBEngineLua.player();
	--	p.selectedRole = avatar
	--
	--	P.phase = P.LoginPhase.enterGame
	--
	--	if P.callback then
	--		P.callback(P.phase, 0, avatar)
	--	end
	--end
end

function P.EnterGame(dbid)
	log("EnterGame dbid:"..tostring(dbid))
	KBEngineLua.player().baseCall.selectAvatarGame(dbid)
	if UnityEngine.Application.platform == UnityEngine.RuntimePlatform.Android then
		--渠道包
		if Config.common.quick_sdk_enable then
			if quicksdk and quicksdk.QuickSDK.getInstance():channelType() > 0 then
				KBEngineLua.player().gameRoleInfo = quicksdk.GameRoleInfo.New()
				KBEngineLua.player().gameRoleInfo.gameRoleBalance = "0"
				KBEngineLua.player().gameRoleInfo.gameRoleID = tostring(avatarInfo.dbid)
				KBEngineLua.player().gameRoleInfo.gameRoleLevel = "1"
				KBEngineLua.player().gameRoleInfo.gameRoleName = avatarInfo.name
				KBEngineLua.player().gameRoleInfo.roleCreateTime = tostring(GetTimeStampNow())

				KBEngineLua.player().gameRoleInfo.partyName = ""
				KBEngineLua.player().gameRoleInfo.serverID = KBEngineLua.serverId
				KBEngineLua.player().gameRoleInfo.serverName = ""
				KBEngineLua.player().gameRoleInfo.vipLevel = "0"
				quicksdk.QuickSDK.getInstance():createRole(KBEngineLua.player().gameRoleInfo)
			end
		end
	end
end

function P.onCreateAvatarResult(errorCode, avatarInfo)
	log("onCreateAvatarResult"..tostring(errorCode))
	--if P.callback then
	--	P.callback(P.phase, errorCode, dic)
	--end
	if errorCode == 0 then
		P.EnterGame(avatarInfo.dbid)
		--local avatar = nil
		--for key, value in pairs(dic) do
		--	avatar = value;
		--	break
		--end

		--local p = KBEngineLua.player();
		--p.selectedRole = avatarInfo

		--P.phase = P.LoginPhase.enterGame
		--if P.callback then
		--	P.callback(P.phase, 0, avatarInfo)
		--end
		--if UnityEngine.Application.platform == UnityEngine.RuntimePlatform.Android then
		--	--渠道包
		--	if Config.common.quick_sdk_enable then
		--		if quicksdk and quicksdk.QuickSDK.getInstance():channelType() > 0 then
		--			KBEngineLua.player().gameRoleInfo = quicksdk.GameRoleInfo.New()
		--			KBEngineLua.player().gameRoleInfo.gameRoleBalance = "0"
		--			KBEngineLua.player().gameRoleInfo.gameRoleID = tostring(avatarInfo.dbid)
		--			KBEngineLua.player().gameRoleInfo.gameRoleLevel = "1"
		--			KBEngineLua.player().gameRoleInfo.gameRoleName = avatarInfo.name
		--			KBEngineLua.player().gameRoleInfo.roleCreateTime = tostring(GetTimeStampNow())
		--
		--			KBEngineLua.player().gameRoleInfo.partyName = ""
		--			KBEngineLua.player().gameRoleInfo.serverID = KBEngineLua.serverId
		--			KBEngineLua.player().gameRoleInfo.serverName = ""
		--			KBEngineLua.player().gameRoleInfo.vipLevel = "0"
		--			quicksdk.QuickSDK.getInstance():createRole(KBEngineLua.player().gameRoleInfo)
		--		end
		--	end
		--end
		
	else
		RootWindowManager.instance:HideCurWindow(true)
		ShowErrorMessageByErrorCode(errorCode)
	end

end

function P.Login(username, password, userAc)
	P.username = username
	P.password = password
	P.userAc = userAc

	P.phase = P.LoginPhase.login

	local channel = AndroidHelper.GetChannel()
	local imei = ""
	local oaid = ""
	--local mac = ""
	local idfa = ""
	local userNameSuffix = ""
	if UnityEngine.Application.platform == UnityEngine.RuntimePlatform.Android then
		userNameSuffix = "Android"
	elseif UnityEngine.Application.platform == UnityEngine.RuntimePlatform.IPhonePlayer then
		userNameSuffix = "IPhonePlayer"
	else
		userNameSuffix = "Android"
	end

	if UnityEngine.Application.platform == UnityEngine.RuntimePlatform.Android then
		local sdkVersion = AndroidHelper.GetSDKInt()
		-- android 10 以上
		if sdkVersion > 28 then
			oaid = AndroidHelper.GetOAID()
		else
			imei = AndroidHelper.GetIMEI()
		end
		--if not oaid and not imei then
		--	mac = GetMacAddress()
		--end
	else
		idfa = IOSHelper.GetIDFA()
		--mac = GetMacAddress()
	end
	local dataTable = {}
	dataTable.channel = channel
	dataTable.unityId = UnityEngine.SystemInfo.deviceUniqueIdentifier
	dataTable.imei = imei
	dataTable.oaid = oaid
	--dataTable.mac = mac
	dataTable.idfa = idfa
	dataTable.identity = P.identity and 1 or 0
	dataTable.isAdult = P.isAdult and 1 or 0
	dataTable.isVisit = not SettingEx.bool.isBound
	local jsonData = json.encode(dataTable)
	local testName = table.find(TestAccount, function (k, v) return v == username end)
	if not testName then
		username = username.."_"..userNameSuffix
	end
	log("Login "..username.."  "..password)
	KBEngineLua.login(username, password, jsonData)
	--KBEngineLua.login(username, password, tostring(channel).."|"..UnityEngine.SystemInfo.deviceUniqueIdentifier.."|"..tostring(imei).."|"..tostring(oaid).."|"..mac)
end

function P.SetServerInfo(serverInfo)
	if serverInfo and KBEngineLua.serverId ~= serverInfo.id then
		SettingEx.string.ServerIP = serverInfo.ip
		SettingEx.int.ServerID = serverInfo.id
		KBEngineLua.ip = serverInfo.ip
		KBEngineLua.serverId = serverInfo.id
		P.curServerInfo = serverInfo
		Event.Brocast("OnSelectServerChange", serverInfo)
	end
end

function P.Register(username, password, userAc)
	P.username = username
	P.password = password
	P.userAc = userAc

	P.phase = P.LoginPhase.createAccount
	-- KBEngineLua.createAccount(P.username, P.password, UnityEngine.SystemInfo.deviceUniqueIdentifier);
	if P.userAc == nil then P.userAc = "" end

	local channel = AndroidHelper.GetChannel()
	local imei = ""
	local oaid = ""
	-- local mac = ""
	local idfa = ""
	local userNameSuffix = ""
	if UnityEngine.Application.platform == UnityEngine.RuntimePlatform.Android then
		userNameSuffix = "Android"
	elseif UnityEngine.Application.platform == UnityEngine.RuntimePlatform.IPhonePlayer then
		userNameSuffix = "IPhonePlayer"
	else
		userNameSuffix = "Android"
	end

	if UnityEngine.Application.platform == UnityEngine.RuntimePlatform.Android then
		local sdkVersion = AndroidHelper.GetSDKInt()
		-- android 10 以上
		if sdkVersion > 28 then
			oaid = AndroidHelper.GetOAID()
		else
			imei = AndroidHelper.GetIMEI()
		end
		--if not oaid and not imei then
		--	mac = GetMacAddress()
		--end
	else
		idfa = IOSHelper.GetIDFA()
		--mac = GetMacAddress()
	end
	local dataTable = {}
	dataTable.channel = channel
	dataTable.unityId = UnityEngine.SystemInfo.deviceUniqueIdentifier
	dataTable.imei = imei
	dataTable.oaid = oaid
	--dataTable.mac = mac
	dataTable.idfa = idfa
	dataTable.identity = P.identity and 1 or 0
	dataTable.isAdult = P.isAdult and 1 or 0
	dataTable.isVisit = false
	local jsonData = json.encode(dataTable)
	local testName = table.find(TestAccount, function (k, v) return v == username end)
	if not testName then
		username = username.."_"..userNameSuffix
	end
	KBEngineLua.createAccount(username, password, jsonData)
	--KBEngineLua.createAccount(P.username, P.password, tostring(channel).."|"..UnityEngine.SystemInfo.deviceUniqueIdentifier.."|"..tostring(imei).."|"..tostring(oaid).."|"..mac)
end

function P.CreateAvatar(avatarName, avatarIndex)
	P.phase = P.LoginPhase.createAvatar
	KBEngineLua.player().baseCall.reqCreateAvatar(avatarName, avatarIndex)
end

function P.Continue()
	if P.phase == P.LoginPhase.login then
	elseif P.phase == P.LoginPhase.createAccount then
	elseif P.phase == P.LoginPhase.getAvatarList then
	elseif P.phase == P.LoginPhase.createAvatar then
	end
end

function P.GetServerTime()
	if P.serverTimeMinusClientTime then
		return P.serverTimeMinusClientTime + os.time()
	end

	return os.time()
end

